console.log("-------------------防抖-----------------");

function showTop() {
  console.log(
    `距离 + ${document.body.scrollTop || document.documentElement.scrollTop}`
  );
}
// window.onscroll=showTop
// 处理一个fn 使得他 delay ms后再调用
function debounce(fn, delay) {
  var timer = null;
  return function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(fn, delay);
  };
}
window.onscroll = debounce(showTop, 1000);

console.log("-------------------节流-----------------");
function showTop() {
  console.log(
    `距离 + ${document.body.scrollTop || document.documentElement.scrollTop}`
  );
}
function throttle(fn, delay) {
  let timer = true; // 工作状态 true 是可以接单的工作状态
  return function () {
    if (!timer) return false;

    timer = false;
    setTimeout(() => {
      fn();
      timer = true;
    }, delay);
  };
}
window.onscroll = throttle(showTop, 1000);
